package datastructure.linkedlist.sigle;

import datastructure.common.AbstractList;

/**
 * 双向循环链表
 *
 * @author cyt
 * @create 2020-11-28 上午 11:33
 */
public class CyLinkedList<E> extends AbstractList<E> {
    private Node first;

    @Override
    public E remove(int index) {
        rangeCheck(index);
        Node<E> node;
        if (index == 0) {
            node = first;
            first = first.next;
        } else {
            Node<E> prev = node(index - 1);
            node = prev.next;
            prev = prev.next.next;
        }
        size--;
        return node.element;
    }

    @Override
    public void clear() {
        size = 0;
        first = null;
    }

    @Override
    public E get(int index) {
        return node(index).element;
    }

    @Override
    public int indexOf(E element) {
        Node<E> node = first;
        if (element == null) {
            for (int i = 0; i < size; i++) {
                if (node.element == null) {
                    return i;
                }
                node = node.next;
            }
        } else {
            for (int i = 0; i < size; i++) {
                if (node.element.equals(element)) {
                    return i;
                }
                node = node.next;
            }
        }
        return ELEMENT_NOT_FOUND;
    }

    @Override
    public void add(int index, E element) {
        rangeCheckOfAdd(index);
        if (index == 0) {
            first = new Node<>(element, first);
        } else {
            Node<E> prev = node(index - 1);
            prev.next = new Node<>(element, prev.next);
        }
        size++;
    }

    @Override
    public E set(int index, E element) {
        Node<E> node = node(index);
        E old = node.element;
        node.element = element;
        return old;
    }

    private Node<E> node(int index) {
        rangeCheck(index);
        Node node = first;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }

    private static class Node<E> {
        E element;
        Node next;

        public Node(E elements, Node next) {
            this.element = elements;
            this.next = next;
        }
    }

    @Override
    public String toString() {
        Node<E> node = first;
        StringBuilder builder = new StringBuilder();
        builder.append("size = ").append(size).append("  [");
        for (Integer i = 0; i < size; i++) {
            builder.append(node.element);
            if (i != size - 1) {
                builder.append(",");
            }
            node = node.next;
        }
        builder.append("]");
        return builder.toString();
    }
}
